﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Leap;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace LeapSample
{

    //内部処理用クラス
    internal class TPos
    {
        public int FingerCount { get; set; }
    }

    //Leap公開用クラス
    public class TItem
    {
        public int FingerCount { get; set; }
    }

    //Leapのループ処理
    internal class SampleListener : Listener
    {
        private TPos Pos;

        public SampleListener()
        {
            this.Pos = new TPos();
        }

        public delegate void DataHandler(object sender, TPos e);
        public event DataHandler Data;
        protected virtual void OnData(TPos e)
        {
            if (Data != null)
                Data(this, e);
        }

        public override void OnFrame(Controller _controller)
        {
            Frame leapFrame = _controller.Frame();
            if (!leapFrame.Hands.Empty)
            {
                this.Pos.FingerCount = leapFrame.Fingers.Count();
                OnData(this.Pos);
            }
        }
    }

    class LeapModel : INotifyPropertyChanged
    {

        private TItem _Item = new TItem();
        public TItem Item
        {
            get
            {
                return this._Item;
            }
            set
            {
                this._Item = value;
                OnPropertyChanged();
            }
        }

        private SampleListener LeapListener;
        private Controller LeapController;

        public LeapModel()
        {
            this.Item = new TItem
            {
                FingerCount = 0
            };
        }

        public void LeapStart()
        {
            this.LeapListener = new SampleListener();
            this.LeapListener.Data += new SampleListener.DataHandler(this.LeapListener_Data);
            this.LeapController = new Controller();
            this.LeapController.AddListener(this.LeapListener);
        }

        public void LeapStop()
        {
            this.LeapController.RemoveListener(this.LeapListener);
            this.LeapController.Dispose();
            this.LeapListener.Data -= new SampleListener.DataHandler(this.LeapListener_Data);
            this.LeapListener = null;
        }

        private void LeapListener_Data(object sender, TPos e)
        {
            this.Item = new TItem
            {
                FingerCount = e.FingerCount
            };
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
